package com.farm.view.task;

import java.sql.SQLException;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.FutureTask;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.TimeoutException;

import org.apache.log4j.Logger;

import com.farm.view.model.utils.OpenOffceUtils;
import com.farm.view.service.ViewTaskServiceInter;
import com.farm.view.task.domain.ConvertAbleTask;

/**
 * 文档转换调度器
 * 
 * @author wangdong
 *
 */
public class TaskDispatcher implements Runnable {
	private static final Logger log = Logger.getLogger(TaskDispatcher.class);

	private ViewTaskServiceInter viewTaskServiceImpl;

	public TaskDispatcher(ViewTaskServiceInter viewTaskService) {
		viewTaskServiceImpl = viewTaskService;
	}

	/**
	 * 睡眠1秒钟
	 */
	private void sleep(long time) {
		try {
			Thread.sleep(time);
		} catch (InterruptedException e1) {
		}
	}

	@Override
	public void run() {
		while (true) {
			ConvertAbleTask task;
			try {
				task = getConvertAbleTask();
			} catch (Exception e1) {
				log.error(e1);
				break;
			}
			try {
				if (task != null) {
					// 如果有可执行任务，就执行
					try {
						ExecutorService executor = Executors.newSingleThreadExecutor();
						FutureTask<Boolean> future = new FutureTask<Boolean>(new SuperConvert(task));
						try {
							// 执行转换任务
							viewTaskServiceImpl.doTaskHandle(task.getTaskId());
							executor.execute(future);
							future.get(task.getOutTime(), TimeUnit.MILLISECONDS); // 取得结果，同时设置超时执行时间为5秒。同样可以用future.get()，不设置执行超时时间取得结果
							// 执行成功
							logSuccess(task);
							viewTaskServiceImpl.submitTaskSuccess(task.getTaskId());
							sleep(1000);
						} catch (TimeoutException e) {
							// 执行超时
							future.cancel(true);
							OpenOffceUtils.shutdown();
							throw new RuntimeException("转换超时!超过" + task.getOutTime() + "毫秒");
						} finally {
							executor.shutdown();
						}
					} catch (Exception e) {
						log.warn("任务失败：" + e.getMessage(), e);
						// 执行报错
						viewTaskServiceImpl.submitTaskFail(task.getTaskId(), e.getMessage());
					}
				} else {
					sleep(2000);
					log.debug("无可执行任务");
					// 如果无可执行任务，就进入下一轮查询
				}
			} catch (Exception e) {
				log.error(e);
			}
		}
	}

	/**
	 * 获得一个可用任务
	 * 
	 * @return
	 * @throws SQLException
	 */
	private ConvertAbleTask getConvertAbleTask() throws SQLException {
		ConvertAbleTask task = viewTaskServiceImpl.getNewRunableTask();
		if (task != null) {
			log.info("开始执行任务...... [" + task.getFileInfo().getFileTitle() + "由" + task.getoModelTitle() + "转换为"
					+ task.gettModelTitle() + "]");
		}
		return task;
	}

	private void logSuccess(ConvertAbleTask task) {
		log.info("执行成功:" + task.getTaskId());
	}
}
